var flag = 0;

function gradeInfo_generate(grade) {
  return new Promise((resolve, reject) => {
    if (!grade) {
      reject();
      return;
    }
    var term = getApp().globalData.userInfo.term;
    var termsTemp = [
      "大一上学期",
      "大一下学期",
      "大二上学期",
      "大二下学期",
      "大三上学期",
      "大三下学期",
      "大四上学期",
      "大四下学期",
      "大五上学期",
      "大五下学期",
      "大六上学期",
      "大六下学期",
    ];
    var terms = [];
    var grades = [];
    var gradeInfo = {};
    var courseCount = 0;
    var courseScore = 0;
    var courseScoresPass = 0; //本学期通过的学分
    var courseCounts = []; //总课程数
    var courseScores = []; //总获得学分数组
    var gpaAve = 0;
    var gpaAves = []; //平均绩点
    var jdfs = []; //加权平均分
    var freeScore = 0; //免修学分
    var scoreAll = 0; //每个学期总加权成绩
    for (let i = 0; i <= term; i++) {
      terms.push(termsTemp[i]);
      courseCount = 0;
      courseScore = 0; //本学期总学分，用来计算gpa
      courseScoresPass = 0; //本学期通过的学分
      gpaAve = 0;
      scoreAll = 0;
      for (let j in grade[i]) {
        courseCount++;
        if (grade[i][j].credit == 0) {
          //返回的数据中，0.5学分会显示为0，应该为源数据的原因
          grade[i][j].credit = 0.5;
        }
        //添加于2020-1-11，用来计算通过的学分
        if (grade[i][j].score >= 60) {
          courseScoresPass += grade[i][j].credit;
        }
        /*于2021-1-20 用于修复免修显示异常 */
        if (grade[i][j].cxckdm == "00") {
          grade[i][j].courseName += "(免修)";
          grade[i][j].score = "免";
          // console(grade[i][j].courseName);
          //不统计免修
          continue;
        }
        /*于2020-1-11 用于处理补考 */
        /*于2021-1-20 用于修复补考、重修显示异常 */
        if (
          grade[i][j].cxckdm == "04" &&
          !grade[i][j].courseName.endsWith("(补考)")
        ) {
          grade[i][j].courseName += "(补考)";
          // courseCount--;//避免本次科目数量加一
          //观察学校教务网发现，学校教务系统计算gpa时补考和之前补考的科目成绩都有计算，
          // 即加入某同学本学期挂了一科，有补考，则在本学期计算gpa时按照两门成绩来算（无论不过或者不过）
        } else if (
          grade[i][j].cxckdm == "02" &&
          !grade[i][j].courseName.endsWith("(重修)")
        ) {
          grade[i][j].courseName += "(重修)";
        }
        courseScore += grade[i][j].credit;
        gpaAve += grade[i][j].gpa * grade[i][j].credit;
        scoreAll += grade[i][j].score * grade[i][j].credit;
      }
      grades.push(grade[i]);
      scoreAll /= courseScore;
      gpaAve /= courseScore;
      gpaAve = parseFloat(String(gpaAve)).toFixed(4);
      scoreAll = parseFloat(String(scoreAll)).toFixed(4);
      courseCounts.push(courseCount);
      //传入的应该是通过的学分
      courseScores.push(courseScoresPass);
      gpaAves.push(gpaAve);
      jdfs.push(scoreAll);
    }
    gradeInfo.grades = grades;
    gradeInfo.terms = terms;
    gradeInfo.courseCounts = courseCounts;
    gradeInfo.courseScores = courseScores;
    gradeInfo.gpaAves = gpaAves;
    gradeInfo.jdfs = jdfs;
    getApp().globalData.gradeInfo = gradeInfo;
    wx.setStorage({
      key: "gradeInfo",
      data: gradeInfo,
    });
    gpa_get(gradeInfo).then(() => resolve());
  });
}

function gpa_get(gradeInfo) {
  return new Promise((reslove) => {
    let url = "study/get_gpas";
    getApp()
      .xutils.request(url)
      .then((res) => {
        var gpasTemp = [];
        for (var i = 1; i < res.data.data.length; i++) {
          var index1 = res.data.data[i].termCode.indexOf("-", 0);
          var index2 = res.data.data[i].termCode.indexOf("-", index1 + 1);
          if (index2 != -1) {
            //剔除学年绩点
            gpasTemp.push(res.data.data[i]);
          }
        }
        var allGradeInfo = res.data.data[0];
        /*总学分bug修复点 */
        var courseScores = gradeInfo.courseScores;
        var gpaAves = gradeInfo.gpaAves;
        var jdfs = gradeInfo.jdfs; //加权平均分
        gradeInfo.allGradeInfo = allGradeInfo; //获得的总学分等信息
        for (var i in gpasTemp) {
          // courseScores[i] = gpasTemp[i].courseCredit;
          // gpaAves[i] = gpasTemp[i].gpa;
          // jdfs[i] = gpasTemp[i].jdf;//加权平均分
        }
        gradeInfo.courseScores = courseScores;
        gradeInfo.gpaAves = gpaAves;
        gradeInfo.jdfs = jdfs;
        getApp().globalData.gradeInfo = gradeInfo;
        reslove();
        wx.setStorage({
          key: "gradeInfo",
          data: gradeInfo,
          success() {},
        });
      });
  });
}

function getGradeList() {
  var terms = getApp().globalData.userInfo.terms;
  // //console.log(terms);
  flag = 0;
  if (!getApp().gradeInfo) {
    getApp().gradeInfo = {};
    getApp().gradeInfo.grades = new Array(
      getApp().globalData.userInfo.terms.length
    );
  }
  for (var i in terms) {
    grade_get(i, terms[i]);
  }
}

async function grade_get(index, termCode, cb) {
  //cb回调函数，用来告诉调用页面执行结果，用于单次调用时使用，循环获取成绩时不会调用
  try {
    let url = "study/get_grades";
    var res = await getApp().xutils.request(url, {
      termCode,
    });
    if (cb) {
      //仅仅刷新单个学期的成绩
      console.log(res);
      var gradeInfo = wx.getStorageSync("gradeInfo");
      gradeInfo.grades.splice(index, 1, res.data.data);
      gradeInfo_generate(gradeInfo.grades).then(() => {
        if (typeof cb == "function") {
          cb();
        }
      });
      return; //return
    } else {
      getApp().gradeInfo.grades.splice(index, 1, res.data.data);
    }
    flag++;
    if (flag == getApp().globalData.userInfo.terms.length) {
      //将所有课程放入本地；
      flag = 0;
      gradeInfo_generate(getApp().gradeInfo.grades);
    }
  } catch (error) {
    getApp().xutils.errorHandler(error);
  }
}

module.exports.getGradeList = getGradeList;
module.exports.grade_get = grade_get;
